//
//  BLDouyuTVSocket.swift
//  danmuDemo
//
//  Created by BigL055 on 16/6/14.
//  Copyright © 2016年 bigL.MoreDemo.com. All rights reserved.
//

import UIKit
import CocoaAsyncSocket

struct postPack {
    var length : UInt32
    var lengthTwice : UInt32
    var postCode : UInt32
}

typealias PostPack = postPack

class BLDouyuTVSocket: NSObject {

    //Socket对象
    var socket : AsyncSocket?
    //服务器数组
    var server = [BLServerModel]()
    //房间ID
    var room : String = ""
    //游客ID
    var vistorID : String = ""
    //弹幕组ID
    var groupID : String = ""
    //心跳keep live
    var connectTimer : NSTimer?
    
    var combieData : NSMutableData?
    
}

extension BLDouyuTVSocket{
    
    func setServerConfig() {

    }
    
    ///连接服务器
    func connectSocketHost() {
        
        socket = AsyncSocket(delegate: self)
        setServerConfig()
        //TODO: 数组可能越界
        guard let sevCfg : BLServerModel = server[5] else{
            return
        }
        
        do{
            try socket!.connectToHost(sevCfg.ip, onPort: sevCfg.port!, withTimeout: 30)
        }catch{
            print(error)
        }
        
    }
    
    ///用户切断链接
    func cutOffSocket() {
        
        connectTimer?.invalidate()
        socket?.disconnect()
    }
    
    ///心跳包
    func longConnectToSocket() {
        //keep live 所发送的信息
    }

}

// MARK: - 回调方法
extension BLDouyuTVSocket : AsyncSocketDelegate {
    
    //连接成功
    func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {

    }
    
    //断开链接
    func onSocketDidDisconnect(sock: AsyncSocket!) {

    }
    
    //发送消息成功之后回调
    func onSocket(sock: AsyncSocket!, didWriteDataWithTag tag: Int) {
        //读取消息
        socket?.readDataWithTimeout(-1, buffer: nil, bufferOffset: 0, maxLength: kMaxBuffer, tag: 0)
    }
    
    
    ///接受数据
    func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
        
        if data.length != 0 {
            var endCode : NSInteger = 0
            //获取data末尾字节
            data.getBytes(&endCode, range: NSMakeRange(data.length - 1, 1))
            if combieData == nil {
                combieData = NSMutableData()
            }
            //如果为0则代表这是一段完整的数据，可以进行解析
            //若无，则需要拼接至一段完整数据才进行解析
            if endCode == 0 {
                combieData?.appendData(data)
                BLSocketData.douyuData(combieData!, isAuthData: false)
                combieData = nil
            }else{
                combieData?.appendData(data)
            }
            socket?.readDataWithTimeout(kReadTimeOut, buffer: nil, bufferOffset: 0, maxLength: kMaxBuffer, tag: 0)
    
        }
    
    }



    func packToData(string : String) -> NSData {
        let stringData : NSMutableData = (string as NSString).stringToHexData()
        let hexLength : UInt32 = UInt32(string.characters.count + 9)
        var pack : PostPack = PostPack(length: hexLength, lengthTwice: hexLength, postCode: kPostCode)
        let postData : NSMutableData = NSData(bytes: &pack, length: (sizeof(UInt32) * 3)).mutableCopy() as! NSMutableData
        postData.appendData(stringData)
        var kend = kEnd
        postData.appendBytes(&kend, length: 1)
        
        return postData
    }
}


